package org.jeecg.modules.gongqiang.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.front.entity.vo.FrontUserhomeOrder;
import org.jeecg.modules.gongqiang.entity.Good;
import org.jeecg.modules.gongqiang.entity.GoodDetail;
import org.jeecg.modules.gongqiang.mapper.GoodDetailMapper;
import org.jeecg.modules.gongqiang.mapper.GoodMapper;
import org.jeecg.modules.gongqiang.service.IGoodService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 商品主表
 * @Author: jeecg-boot
 * @Date:   2024-06-12
 * @Version: V1.0
 */
@Service
public class GoodServiceImpl extends ServiceImpl<GoodMapper, Good> implements IGoodService {

	@Resource
	private GoodMapper goodMapper;
	@Resource
	private GoodDetailMapper goodDetailMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(Good good, List<GoodDetail> goodDetailList) {
		goodMapper.insert(good);
		int stockNum=0;
		if(goodDetailList!=null && goodDetailList.size()>0) {
			for(GoodDetail entity:goodDetailList) {
				//外键设置
				stockNum+=entity.getStockNum();
				entity.setGoodId(good.getId());
				goodDetailMapper.insert(entity);
			}
		}
		good.setStockNum(stockNum);
		goodMapper.updateById(good);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(Good good,List<GoodDetail> goodDetailList) {

		goodMapper.updateById(good);
		//1.先删除子表数据
		goodDetailMapper.deleteByMainId(good.getId());
		int stockNum=0;
		//2.子表数据重新插入
		if(goodDetailList!=null && goodDetailList.size()>0) {
			for(GoodDetail entity:goodDetailList) {
				//外键设置
				stockNum+=entity.getStockNum();
				entity.setGoodId(good.getId());
				goodDetailMapper.insert(entity);
			}
		}
		good.setStockNum(stockNum);
		goodMapper.updateById(good);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		goodDetailMapper.deleteByMainId(id);
		goodMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			goodDetailMapper.deleteByMainId(id.toString());
			goodMapper.deleteById(id);
		}
	}

	@Override
	public IPage<FrontUserhomeOrder> pageIndexList(Page<FrontUserhomeOrder> page, Integer status,Integer userId) {
		return this.baseMapper.pageIndexList(page, status,userId);
	}

	@Override
	public FrontUserhomeOrder pageIndex(String orderId) {
		return this.baseMapper.pageIndex(orderId);
	}

}
